import socket
import json
import sys
import time
import pygame
import threading

# 初始化pygame
pygame.init()
screen = pygame.display.set_mode((500, 750))
pygame.display.set_caption("飞行棋 - 客户端")

# 棋盘上边界
y_top = 100
# 颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (248, 65, 47)
yellow = (248, 212, 2)
green = (62, 207, 140)
blue = (6, 183, 227)
gray = (128, 128, 128)

colors = [red, yellow, blue, green]

# 红色棋子坐标
red_chess = [(46.2, 407.4 + y_top), (46.2, 447.4 + y_top), (86.2, 407.4 + y_top), (86.2, 447.4 + y_top)]
# 黄色棋子坐标
yellow_chess = [(46.2, 40 + y_top), (46.2, 80 + y_top), (86.2, 40 + y_top), (86.2, 80 + y_top)]
# 蓝色棋子坐标
blue_chess = [(454.4, 40 + y_top), (454.4, 80 + y_top), (414.4, 40 + y_top), (414.4, 80 + y_top)]
# 绿色棋子坐标
green_chess = [(455, 447.4 + y_top), (455, 407.4 + y_top), (415, 447.4 + y_top), (415, 407.4 + y_top)]

# 棋子
chess = [
    [
        [46.2, 407.4 + y_top, False, False],
        [46.2, 447.4 + y_top, False, False],
        [86.2, 407.4 + y_top, False, False],
        [86.2, 447.4 + y_top, False, False]
    ],
    [
        [46.2, 40 + y_top, False, False],
        [46.2, 80 + y_top, False, False],
        [86.2, 40 + y_top, False, False],
        [86.2, 80 + y_top, False, False]
    ],
    [
        [454.4, 40 + y_top, False, False],
        [454.4, 80 + y_top, False, False],
        [414.4, 40 + y_top, False, False],
        [414.4, 80 + y_top, False, False]
    ],
    [
        [455, 447.4 + y_top, False, False],
        [455, 407.4 + y_top, False, False],
        [415, 447.4 + y_top, False, False],
        [415, 407.4 + y_top, False, False]
    ]
]

# 原始坐标
row_chess_pos = [red_chess, yellow_chess, blue_chess, green_chess]

# 起飞点坐标
start_pos = [(128.2, 461.4 + y_top), (33.2, 122 + y_top), (372.4, 26 + y_top), (469, 365.4 + y_top)]

# 门口第一个格子的坐标
start_pos_first = [(157.6, 445.2 + y_top), (49.4, 151.4 + y_top), (342, 43 + y_top), (451.4, 335.8 + y_top)]

# 棋盘格子坐标（4， 2）（5，3）（17(139.4)， 3）（18， 0）（30，0）（31(360.6)，1）（43，1）（44， 2）52格
grids = [(157.6, 445.2 + y_top), (149.6, 415 + y_top), (149.6, 383.6 + y_top), (157.6, 354.4 + y_top),
         (139, 336.4 + y_top), (109.8, 343.8 + y_top), (78.4, 343.8 + y_top), (49.2, 335.8 + y_top),
         (41.2, 306.6 + y_top), (41.2, 275.2 + y_top), (41.2, 243.8 + y_top), (41.2, 212.4 + y_top),
         (41.2, 181 + y_top), (49.4, 151.4 + y_top), (78.8, 143.4 + y_top), (110.2, 143.4 + y_top),
         (139, 151.4 + y_top), (158, 132.8 + y_top), (150, 103.6 + y_top), (150, 72.4 + y_top), (158, 43 + y_top),
         (187.2, 35 + y_top), (218.6, 35 + y_top), (250, 35 + y_top), (281.4, 35 + y_top), (312.8, 35 + y_top),
         (342, 43 + y_top), (350, 72.2 + y_top), (350, 103.6 + y_top), (342, 132.8 + y_top), (361.6, 151.4 + y_top),
         (389.8, 143.4 + y_top), (421.2, 143.4 + y_top), (451.4, 151.4 + y_top), (459.4, 181 + y_top),
         (459.4, 212.4 + y_top), (459.4, 243.8 + y_top), (459.4, 275.2 + y_top), (459.4, 306.6 + y_top),
         (451.4, 335.8 + y_top), (422.2, 343.8 + y_top), (390.8, 343.8 + y_top), (361.6, 335.8 + y_top),
         (343, 354.4 + y_top), (351, 383.6 + y_top), (351, 415 + y_top), (343, 444.2 + y_top), (313.8, 452.4 + y_top),
         (282.4, 452.4 + y_top), (250, 452.4 + y_top), (219.4, 452.4 + y_top), (187.8, 452.4 + y_top)]

# 降落格子坐标（49，10，23，36）
red_grids = [(250, 452.4 + y_top), (250, 415.2 + y_top), (250, 384.8 + y_top), (250, 353.4 + y_top), (250, 322 + y_top),
             (250, 290.6 + y_top), (250, 264.6 + y_top)]
yellow_grids = [(41.2, 243.8 + y_top), (78.4, 243.8 + y_top), (109.8, 243.8 + y_top), (141.2, 243.8 + y_top),
                (172.6, 243.8 + y_top), (204, 243.8 + y_top), (230, 243.8 + y_top)]
blue_grids = [(250, 35 + y_top), (250, 72.2 + y_top), (250, 103.6 + y_top), (250, 135.2 + y_top),
              (250, 166.6 + y_top), (250, 197.8 + y_top), (250, 223.8 + y_top)]
green_grids = [(459.4, 243.8 + y_top), (420.6, 243.8 + y_top), (389.2, 243.8 + y_top), (357.8, 243.8 + y_top), (326.4, 243.8 + y_top),
               (295, 243.8 + y_top), (269, 243.8 + y_top)]

end_grids = [red_grids, yellow_grids, blue_grids, green_grids]

# 计数器
red_counter = 0
yellow_counter = 0
blue_counter = 0
green_counter = 0
counter = [red_counter, yellow_counter, blue_counter, green_counter]

# 游戏轮数
game_round = 0

# 骰子点数
dice = 6

# 阶段(0为掷骰子阶段,1为选择和移动棋子阶段)
stage = 0

# 掷骰子标记
dice_flag = False

board = pygame.image.load("board.png")

# 字体
font = pygame.font.SysFont("simhei", 10, bold=True)
num_font = pygame.font.SysFont("simhei", 80)
dice_font = pygame.font.SysFont("simhei", 30)
mess_font = pygame.font.SysFont("simhei", 20)
arrived_font = pygame.font.SysFont("simhei", 20, bold=True)

# 创建一个时钟对象
clock = pygame.time.Clock()

# 客户端变量
HOST = '192.168.43.186'
PORT = 65432
player_id = None
current_player = 0
game_started = False
players_ready = []
total_players = 0
waiting_for_move = False  # 是否等待移动棋子

# 网络连接
client_socket = None
connected = False

"""---------------------------------------------------网络连接-----------------------------------------------------"""


def connect_to_server():
    """连接到服务器"""
    global client_socket, connected
    try:
        client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client_socket.connect((HOST, PORT))
        connected = True
        print("成功连接到服务器")
        return True
    except Exception as e:
        print(f"无法连接到服务器: {e}")
        return False


def send_message(message):
    """发送消息到服务器"""
    if connected and client_socket:
        try:
            json_message = json.dumps(message)
            client_socket.send(json_message.encode('utf-8'))
        except Exception as e:
            print(f"发送消息失败: {e}")
            import traceback
            traceback.print_exc()


def receive_messages():
    """接收服务器消息的线程函数"""
    global player_id, game_started, current_player, dice, game_round, chess, total_players, stage, waiting_for_move

    while connected:
        try:
            data = client_socket.recv(4096).decode('utf-8')
            if not data:
                print("服务器关闭了连接")
                break

            message = json.loads(data)
            msg_type = message.get('type')

            if msg_type == 'assign_player_id':
                player_id = message.get('player_id')
                print(f"分配到玩家ID: {player_id}")

            elif msg_type == 'player_joined':
                total_players = message.get('total_players')
                print(f"新玩家加入，当前玩家数: {total_players}")

            elif msg_type == 'player_left':
                total_players = message.get('total_players')
                left_player_id = message.get('player_id')
                print(f"玩家 {left_player_id} 离开，当前玩家数: {total_players}")
                # 如果离开的是自己，可能需要特殊处理
                if left_player_id == player_id:
                    print("你已离开游戏")

            elif msg_type == 'game_start':
                game_started = True
                initial_state = message.get('initial_state')
                current_player = initial_state.get('current_player', 0)
                dice = initial_state.get('dice_value', 6)
                game_round = initial_state.get('game_round', 0)
                if 'chess_positions' in initial_state:
                    chess = initial_state.get('chess_positions')
                print("游戏开始!")

            elif msg_type == 'dice_result':
                dice_player = message.get('player_id')
                dice_value = message.get('dice_value')
                dice = dice_value
                current_player = message.get('current_player', current_player)
                stage = message.get('stage', stage)
                waiting_for_move = (stage == 1)
                print(f"玩家 {dice_player} 掷出 {dice_value}点, 阶段: {stage}")

            elif msg_type == 'chess_moved':
                moved_player = message.get('player_id')
                chess_id = message.get('chess_id')
                dice_value = message.get('dice_value')
                # 本地移动棋子
                move_chess(moved_player, chess_id, dice_value)
                # 更新本地棋子状态
                # if 'chess_positions' in message:
                #     chess = message.get('chess_positions')
                # print(f"玩家 {moved_player} 移动棋子 {chess_id}，步数 {dice_value}")
                waiting_for_move = False
                if moved_player == player_id:
                    stage = 0

            elif msg_type == 'player_switched':
                # 切换到下一个玩家
                current_player = message.get('current_player', current_player)
                stage = message.get('stage', stage)
                print(f"切换到玩家: {current_player}, 阶段：{stage}")

        except json.JSONDecodeError:
            print("接收到了无效的JSON数据")
        except ConnectionResetError:
            print("与服务器的连接已断开")
            break
        except Exception as e:
            print(f"接收消息时出错: {e}")
            import traceback
            traceback.print_exc()
            break


"""----------------------------------------------    游戏行为     ---------------------------------------------"""


def draw_board(player_id):
    """绘制游戏棋盘"""
    screen.blit(board, (0, 0))

    # 显示玩家信息
    if player_id is not None:
        player_info = mess_font.render(f"你的玩家ID: {player_id}", True, black)
        screen.blit(player_info, (0, 0))

    if not game_started:
        status_text = mess_font.render("等待其他玩家加入...", True, black)
        screen.blit(status_text, (0, 30))
        if total_players > 0:
            players_text = mess_font.render(f"当前玩家数: {total_players}", True, black)
            screen.blit(players_text, (0, 60))
    else:
        if current_player == player_id:
            print(current_player)
            if stage == 0:
                action_person = mess_font.render("轮到你了! 点击掷骰子", True, black)
            else:
                action_person = mess_font.render("轮到你了! 请选择要移动的棋子", True, black)
        else:
            action_person = mess_font.render(f"当前回合玩家: {current_player}", True, black)
        screen.blit(action_person, (0, 30))

    # 绘制棋子
    for i in range(4):
        c = (player_id + i + 1) % 4
        for p in range(4):
            if chess[c][p][3]:
                text = arrived_font.render("进", True, black)
                screen.blit(pygame.transform.rotate(text, -90 * c), (chess[c][p][0] - text.get_width() / 2,
                                                                     chess[c][p][1] - text.get_height() / 2))
            else:
                pygame.draw.circle(screen, colors[c], (chess[c][p][0], chess[c][p][1]), 12)

    # 掷骰子按钮
    if game_started and current_player == player_id and stage == 0:
        pygame.draw.rect(screen, colors[player_id], (50, 630, 100, 50), 5)
        text = dice_font.render("掷骰子", True, colors[player_id])
        screen.blit(text, (55, 640))
    elif game_started and current_player == player_id and stage == 1:
        move_text = dice_font.render("选择棋子", True, colors[player_id])
        screen.blit(move_text, (55, 640))

    # 骰子点数显示框
    pygame.draw.rect(screen, colors[current_player], (270, 600, 100, 100), 5)
    # 绘制骰子点数
    if not dice_flag:
        text = num_font.render(str(dice), True, black)
        screen.blit(text, (300, 600))


# def draw_dice_animation():
#     """掷骰子动画"""
#     global dice_flag
#     dice_flag = True
#     for m in range(10):
#         for n in range(1, 7):
#             draw_board()
#             text = num_font.render(str(n), True, black)
#             screen.blit(text, (300, 600))
#             if m == 9 and n == dice:
#                 break
#             pygame.display.flip()
#             time.sleep(0.03)
#     dice_flag = False


def choose_chess(pos):
    """选择要移动的棋子"""
    x, y = pos
    # 判断玩家是否正确地选中了要移动的棋子
    for j in range(len(chess[player_id])):
        if chess[player_id][j][0] - 12 <= x <= chess[player_id][j][0] + 12 and\
                chess[player_id][j][1] - 12 <= y <= chess[player_id][j][1] + 12:
            if (chess[player_id][j][2] is False and dice == 6) or (chess[player_id][j][2] is True):
                return j
            break
    return None


def move_chess(player_id, j, dice):
    """移动棋子"""
    global stage, game_round
    moved_chess = chess[player_id]
    # 判断棋子是否起飞
    if moved_chess[j][2]:
        # 判断棋子是否在终点格子中
        if (moved_chess[j][0], moved_chess[j][1]) in end_grids[player_id]:
            grid_index = end_grids[player_id].index((moved_chess[j][0], moved_chess[j][1]))
            for k in range(grid_index + 1, grid_index + dice + 1):
                # 当索引k超过终点格子数时，索引k取12 - k
                if k > 6:
                    k = 12 - k
                x = (moved_chess[j][0] - end_grids[player_id][k][0]) / 35
                y = (moved_chess[j][1] - end_grids[player_id][k][1]) / 35
                while moved_chess[j][0] != end_grids[player_id][k][0] or moved_chess[j][1] != end_grids[player_id][k][1]:
                    if (-1 <= moved_chess[j][0] - end_grids[player_id][k][0] <= 1 and x != 0) or (
                            -1 <= moved_chess[j][1] - end_grids[player_id][k][1] <= 1 and y != 0):
                        moved_chess[j][0] = end_grids[player_id][k][0]
                        moved_chess[j][1] = end_grids[player_id][k][1]
                    else:
                        moved_chess[j][0] = moved_chess[j][0] - x
                        moved_chess[j][1] = moved_chess[j][1] - y
                    draw_board(player_id)
                    pygame.display.flip()
                    time.sleep(0.02)
        # 判断棋子是否在正常的格子中
        elif (moved_chess[j][0], moved_chess[j][1]) in grids:
            grid_index = grids.index((moved_chess[j][0], moved_chess[j][1]))
            for k in range(grid_index + 1, grid_index + dice + 1):
                # 当索引k超过棋子格子数时，索引k取余棋子格子数
                k = k % len(grids)
                x = (moved_chess[j][0] - grids[k][0]) / 35
                y = (moved_chess[j][1] - grids[k][1]) / 35
                while moved_chess[j][0] != grids[k][0] or moved_chess[j][1] != grids[k][1]:
                    if (-1 <= moved_chess[j][0] - grids[k][0] <= 1 and x != 0) or \
                            (-1 <= moved_chess[j][1] - grids[k][1] <= 1 and y != 0):
                        moved_chess[j][0] = grids[k][0]
                        moved_chess[j][1] = grids[k][1]
                    else:
                        moved_chess[j][0] = moved_chess[j][0] - x
                        moved_chess[j][1] = moved_chess[j][1] - y
                    draw_board(player_id)
                    pygame.display.flip()
                    time.sleep(0.02)
                # 判断棋子是否在终点门口
                if (moved_chess[j][0], moved_chess[j][1]) == end_grids[player_id][0] and k != grid_index + dice + 1:
                    for e in range(1, grid_index + dice + 1 - k):
                        x = (moved_chess[j][0] - end_grids[player_id][e][0]) / 35
                        y = (moved_chess[j][1] - end_grids[player_id][e][1]) / 35
                        while moved_chess[j][0] != end_grids[player_id][e][0] or moved_chess[j][1] != end_grids[player_id][e][1]:
                            if (-1 <= moved_chess[j][0] - end_grids[player_id][e][0] <= 1 and x != 0) or (
                                    -1 <= moved_chess[j][1] - end_grids[player_id][e][1] <= 1 and y != 0):
                                moved_chess[j][0] = end_grids[player_id][e][0]
                                moved_chess[j][1] = end_grids[player_id][e][1]
                            else:
                                moved_chess[j][0] = moved_chess[j][0] - x
                                moved_chess[j][1] = moved_chess[j][1] - y
                            draw_board(player_id)
                            pygame.display.flip()
                            time.sleep(0.02)
                    break
        # 判断棋子是否在起始格子中
        elif (moved_chess[j][0], moved_chess[j][1]) in start_pos:
            x = (moved_chess[j][0] - start_pos_first[player_id][0]) / 35
            y = (moved_chess[j][1] - start_pos_first[player_id][1]) / 35
            while moved_chess[j][0] != start_pos_first[player_id][0] or moved_chess[j][1] != start_pos_first[player_id][1]:
                if (-1 <= moved_chess[j][0] - start_pos_first[player_id][0] <= 1 and x != 0) or (
                        -1 <= moved_chess[0][1] - start_pos_first[player_id][1] <= 1 and y != 0):
                    moved_chess[j][0] = start_pos_first[player_id][0]
                    moved_chess[j][1] = start_pos_first[player_id][1]
                else:
                    moved_chess[j][0] = moved_chess[j][0] - x
                    moved_chess[j][1] = moved_chess[j][1] - y
                draw_board(player_id)
                pygame.display.flip()
                time.sleep(0.02)
            grid_index = grids.index((moved_chess[j][0], moved_chess[j][1]))
            for k in range(grid_index + 1, grid_index + dice):
                k = k % len(grids)
                x = (moved_chess[j][0] - grids[k][0]) / 35
                y = (moved_chess[j][1] - grids[k][1]) / 35
                while moved_chess[j][0] != grids[k][0] or moved_chess[j][1] != grids[k][1]:
                    if (-1 <= moved_chess[j][0] - grids[k][0] <= 1 and x != 0) or \
                            (-1 <= moved_chess[j][1] - grids[k][1] <= 1 and y != 0):
                        moved_chess[j][0] = grids[k][0]
                        moved_chess[j][1] = grids[k][1]
                    else:
                        moved_chess[j][0] = moved_chess[j][0] - x
                        moved_chess[j][1] = moved_chess[j][1] - y
                    draw_board(player_id)
                    pygame.display.flip()
                    time.sleep(0.02)
    else:
        x = (moved_chess[j][0] - start_pos[player_id][0]) / 6
        y = (moved_chess[j][1] - start_pos[player_id][1]) / 6
        while moved_chess[j][0] != start_pos[player_id][0] or moved_chess[j][1] != start_pos[player_id][1]:
            if (-1 <= moved_chess[j][0] - start_pos[player_id][0] <= 1 and x != 0) or (
                    -1 <= moved_chess[0][1] - start_pos[player_id][1] <= 1 and y != 0):
                moved_chess[j][0] = start_pos[player_id][0]
                moved_chess[j][1] = start_pos[player_id][1]
            else:
                moved_chess[j][0] = moved_chess[j][0] - x
                moved_chess[j][1] = moved_chess[j][1] - y
            draw_board(player_id)
            pygame.display.flip()
            time.sleep(0.02)
    # 起飞状态改为True
    moved_chess[j][2] = True
    # 飞行前或跳跃前碰撞
    check_collision(j, player_id)
    # 处理飞行情况
    fly_chess(j, player_id)
    # 飞行后或跳跃前碰撞
    check_collision(j, player_id)
    # 处理跳跃情况
    jump_chess(j, player_id)
    # 跳跃后碰撞
    check_collision(j, player_id)
    # 处理跳跃后飞行情况
    fly_chess(j, player_id)
    # 飞行后碰撞
    check_collision(j, player_id)
    # 判断棋子是否到达终点
    arrived_end(j, player_id)
    # 更改为掷骰子阶段
    stage = 0


def arrived_end(j, player_id):
    """到达终点"""
    color = player_id
    if (chess[color][j][0], chess[color][j][1]) == end_grids[color][-1]:
        x = (end_grids[color][-1][0] - row_chess_pos[color][j][0]) / 40
        y = (end_grids[color][-1][1] - row_chess_pos[color][j][1]) / 40
        while chess[color][j][0] != row_chess_pos[color][j][0] or chess[color][j][1] != row_chess_pos[color][j][1]:
            if (-1 <= chess[color][j][0] - row_chess_pos[color][j][0] <= 1 and x != 0) or (
                    -1 <= chess[color][j][1] - row_chess_pos[color][j][1] <= 1 and y != 0):
                chess[color][j][0] = row_chess_pos[color][j][0]
                chess[color][j][1] = row_chess_pos[color][j][1]
            else:
                chess[color][j][0] = chess[color][j][0] - x
                chess[color][j][1] = chess[color][j][1] - y
            draw_board(player_id)
            pygame.display.flip()
            time.sleep(0.02)
        chess[color][j][3] = True


def check_collision(j, player_id):
    """检测碰撞"""
    color = player_id
    for t in range(1, 4):
        for g in range(4):
            if chess[(color + t) % 4][g][0] == chess[color][j][0] and chess[(color + t) % 4][g][1] == chess[color][j][1]:
                x = (chess[(color + t) % 4][g][0] - row_chess_pos[(color + t) % 4][g][0]) / 40
                y = (chess[(color + t) % 4][g][1] - row_chess_pos[(color + t) % 4][g][1]) / 40
                while chess[(color + t) % 4][g][0] != row_chess_pos[(color + t) % 4][g][0] or\
                        chess[(color + t) % 4][g][1] != row_chess_pos[(color + t) % 4][g][1]:
                    if (-1 <= chess[(color + t) % 4][g][0] - row_chess_pos[(color + t) % 4][g][0] <= 1 and x != 0) or \
                            (-1 <= chess[(color + t) % 4][g][1] - row_chess_pos[(color + t) % 4][g][1] <= 1 and y != 0):
                        chess[(color + t) % 4][g][0] = row_chess_pos[(color + t) % 4][g][0]
                        chess[(color + t) % 4][g][1] = row_chess_pos[(color + t) % 4][g][1]
                    else:
                        chess[(color + t) % 4][g][0] = chess[(color + t) % 4][g][0] - x
                        chess[(color + t) % 4][g][1] = chess[(color + t) % 4][g][1] - y
                    draw_board(player_id)
                    pygame.display.flip()
                    time.sleep(0.02)
                chess[(color + t) % 4][g][2] = False


def jump_chess(j, player_id):
    """跳跃"""
    color = player_id
    if (chess[color][j][0], chess[color][j][1]) in grids and\
            (chess[color][j][0], chess[color][j][1]) not in end_grids[color]:
        grid_index = grids.index((chess[color][j][0], chess[color][j][1]))
        if grid_index % 4 == (color + 1) % 4:
            # 格子颜色与棋子颜色相同，则进行跳跃
            x = (chess[color][j][0] - grids[(grid_index + 4) % len(grids)][0]) / 40
            y = (chess[color][j][1] - grids[(grid_index + 4) % len(grids)][1]) / 40
            while chess[color][j][0] != grids[(grid_index + 4) % len(grids)][0] or\
                    chess[color][j][1] != grids[(grid_index + 4) % len(grids)][1]:
                if (-1 <= chess[color][j][0] - grids[(grid_index + 4) % len(grids)][0] <= 1 and x != 0) or \
                        (-1 <= chess[color][j][1] - grids[(grid_index + 4) % len(grids)][1] <= 1 and y != 0):
                    chess[color][j][0] = grids[(grid_index + 4) % len(grids)][0]
                    chess[color][j][1] = grids[(grid_index + 4) % len(grids)][1]
                else:
                    chess[color][j][0] = chess[color][j][0] - x
                    chess[color][j][1] = chess[color][j][1] - y
                draw_board(player_id)
                pygame.display.flip()
                time.sleep(0.02)


def fly_chess(j, player_id):
    """飞行"""
    color = player_id
    if (chess[color][j][0], chess[color][j][1]) in grids:
        grid_index = grids.index((chess[color][j][0], chess[color][j][1]))
        if (grid_index - 17 >= 0 and (grid_index - 17) / 13 == color) or \
                (grid_index - 17 < 0 and (grid_index + 52 - 17) / 13 == color):
            x = (chess[color][j][0] - grids[(grid_index + 12) % len(grids)][0]) / 40
            y = (chess[color][j][1] - grids[(grid_index + 12) % len(grids)][1]) / 40
            while chess[color][j][0] != grids[(grid_index + 12) % len(grids)][0] or\
                    chess[color][j][1] != grids[(grid_index + 12) % len(grids)][1]:
                if (-1 <= chess[color][j][0] - grids[(grid_index + 12) % len(grids)][0] <= 1 and x != 0) or \
                        (-1 <= chess[color][j][1] - grids[(grid_index + 12) % len(grids)][1] <= 1 and y != 0):
                    chess[color][j][0] = grids[(grid_index + 12) % len(grids)][0]
                    chess[color][j][1] = grids[(grid_index + 12) % len(grids)][1]
                else:
                    chess[color][j][0] = chess[color][j][0] - x
                    chess[color][j][1] = chess[color][j][1] - y
                draw_board(player_id)
                pygame.display.flip()
                time.sleep(0.02)


def main():
    """主函数"""
    global game_started, current_player, dice, game_round, player_id, stage

    # 连接到服务器
    if not connect_to_server():
        print("无法连接到服务器，请确保服务器正在运行")
        return

    # 启动接收消息的线程
    receive_thread = threading.Thread(target=receive_messages)
    receive_thread.daemon = True
    receive_thread.start()

    # 等待获取player_id
    timeout = time.time() + 10  # 10秒超时
    while player_id is None and time.time() < timeout:
        time.sleep(0.1)

    if player_id is None:
        print("获取玩家ID超时")
        return

    # 发送准备就绪消息
    send_message({
        'type': 'player_ready',
        'player_id': player_id
    })

    # 主循环
    running = True
    while running:
        for event in pygame.event.get():
            # 检测窗口关闭事件
            if event.type == pygame.QUIT:
                running = False

            # 检测鼠标点击事件
            if event.type == pygame.MOUSEBUTTONDOWN:
                # 掷骰子阶段
                if game_started and current_player == player_id and stage == 0:
                    x, y = pygame.mouse.get_pos()
                    if 50 <= x <= 150 and 630 <= y <= 680:
                        send_message({
                            'type': 'roll_dice',
                            'player_id': player_id,
                            'chess': chess[player_id]
                        })
                # 移动棋子阶段
                elif game_started and current_player == player_id and stage == 1:
                    j = choose_chess(pygame.mouse.get_pos())
                    if j is not None:
                        send_message({
                            'type': 'move_chess',
                            'player_id': player_id,
                            'chess_id': j
                        })

        # 绘制棋盘
        draw_board(player_id)
        # 设置帧率
        clock.tick(60)
        # 刷新
        pygame.display.flip()

    # 关闭连接
    global connected
    connected = False
    if client_socket:
        try:
            client_socket.close()
        except:
            pass

    pygame.quit()
    sys.exit()


if __name__ == "__main__":
    main()
